Skip to content

feat(jax): freeze models with hessian output#5608

Open
njzjz wants to merge 6 commits into
deepmodeling:masterfrom
njzjz:feat/jax-hessian-freeze
Open

feat(jax): freeze models with hessian output#5608
njzjz wants to merge 6 commits into
deepmodeling:masterfrom
njzjz:feat/jax-hessian-freeze

Conversation

@njzjz

@njzjz njzjz commented Jun 29, 2026

Copy link
Copy Markdown
Member

Summary

  • add dp freeze --hessian support for the JAX backend
  • propagate the Hessian flag through JAX .jax, .hlo, and .savedmodel serialization
  • mark HLO energy output definitions as Hessian-enabled and request Hessian outputs during JAX inference

Tests

  • source venv/bin/activate && pytest source/tests/jax/test_training.py::TestJAXTraining::test_freeze_entrypoint_uses_checkpoint_pointer source/tests/jax/test_training.py::TestJAXTraining::test_main_dispatches_freeze source/tests/jax/test_training.py::TestJAXTraining::test_hlo_hessian_mode_updates_output_def source/tests/jax/test_training.py::TestJAXTraining::test_deep_eval_requests_hessian_for_hessian_model -q
  • source venv/bin/activate && ruff check .
  • source venv/bin/activate && ruff format .

Summary by CodeRabbit

  • New Features

    • Added a --hessian option to the model freezing command to include Hessian information in exported outputs.
    • Evaluation now detects Hessian-capable models and can request Hessian-related derivative outputs when enabled.
  • Bug Fixes

    • Preserved Hessian mode during export so the frozen model metadata and output definitions correctly reflect Hessian settings.
    • Updated energy output handling to use Hessian-aware energy definitions when Hessian mode is active.
  • Tests

    • Added/updated regression and CLI tests to verify Hessian flag propagation through freezing and correct Hessian-aware output selection in evaluation.

@dosubot dosubot Bot added the new feature label Jun 29, 2026
@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: a6f2b78a-f21c-4509-840e-d689f42a668b

📥 Commits

Reviewing files that changed from the base of the PR and between 7f2b958 and bab82b1.

📒 Files selected for processing (2)
  • deepmd/jax/infer/deep_eval.py
  • source/tests/jax/test_training.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • deepmd/jax/infer/deep_eval.py

📝 Walkthrough

Walkthrough

Adds a --hessian option to JAX freezing. The flag propagates through freeze and serialization paths, enabling Hessian mode and persisting hessian_mode. HLO exposes Hessian-aware energy outputs, while DeepEval requests Hessian data and reports Hessian mode.

Changes

JAX freeze Hessian support

Layer / File(s) Summary
HLO output definitions and DeepEval detection
deepmd/jax/model/hlo.py, deepmd/jax/infer/deep_eval.py
Adds energy_hessian, remaps energy output definitions when Hessian mode is enabled, includes Hessian requests, and exposes get_has_hessian().
Serialization Hessian propagation
deepmd/jax/utils/serialization.py, deepmd/jax/jax2tf/serialization.py
Adds the hessian parameter, enables Hessian mode for restored models, updates model metadata, and forwards the option across export formats.
CLI and freeze entrypoint wiring
deepmd/main.py, deepmd/jax/entrypoints/freeze.py
Adds the --hessian CLI flag and forwards the option from freeze() to serialization.
Regression coverage
source/tests/jax/test_training.py
Tests Hessian forwarding, HLO output definitions, and DeepEval Hessian requests.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant freeze
  participant serialization
  participant model
  participant HLO
  CLI->>freeze: freeze --hessian
  freeze->>serialization: deserialize_to_file(hessian=True)
  serialization->>model: enable_hessian()
  serialization->>serialization: set model_def_script hessian_mode
  serialization-->>HLO: export Hessian-enabled model
Loading

Possibly related PRs

Suggested reviewers: njzjz-bot, wanghan-iapcm

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding Hessian output support to JAX freeze.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
source/tests/jax/test_training.py (1)

199-214: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert hessian in the dispatcher call.

This still passes if main() drops args.hessian before invoking freeze(). Please assert the patched call carries the new flag as well.

Suggested test tightening
         main(args)

         freeze_entrypoint.assert_called_once()
+        self.assertIn("hessian", freeze_entrypoint.call_args.kwargs)
+        self.assertFalse(freeze_entrypoint.call_args.kwargs["hessian"])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@source/tests/jax/test_training.py` around lines 199 - 214, The test for the
JAX CLI freeze dispatch is too loose because it only checks that the patched
freeze entrypoint was called. Tighten test_main_dispatches_freeze in
test_training.py by asserting the call includes the hessian flag from the
argparse.Namespace, so main() must forward args.hessian into
deepmd.jax.entrypoints.main.freeze rather than dropping it. Use the existing
freeze_entrypoint mock and verify its call arguments reflect the new flag.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@source/tests/jax/test_training.py`:
- Around line 199-214: The test for the JAX CLI freeze dispatch is too loose
because it only checks that the patched freeze entrypoint was called. Tighten
test_main_dispatches_freeze in test_training.py by asserting the call includes
the hessian flag from the argparse.Namespace, so main() must forward
args.hessian into deepmd.jax.entrypoints.main.freeze rather than dropping it.
Use the existing freeze_entrypoint mock and verify its call arguments reflect
the new flag.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 44d1886d-fd38-4bbe-a056-c56edc3c92fc

📥 Commits

Reviewing files that changed from the base of the PR and between 1550599 and 16058df.

📒 Files selected for processing (7)
  • deepmd/jax/entrypoints/freeze.py
  • deepmd/jax/infer/deep_eval.py
  • deepmd/jax/jax2tf/serialization.py
  • deepmd/jax/model/hlo.py
  • deepmd/jax/utils/serialization.py
  • deepmd/main.py
  • source/tests/jax/test_training.py

@njzjz njzjz force-pushed the feat/jax-hessian-freeze branch from 16058df to 6eabd63 Compare June 29, 2026 18:34
Comment thread deepmd/jax/utils/serialization.py Fixed
@codecov

codecov Bot commented Jun 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.41176% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.52%. Comparing base (2b6cd22) to head (bab82b1).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
deepmd/jax/utils/serialization.py 66.66% 6 Missing ⚠️
deepmd/jax/jax2tf/serialization.py 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #5608      +/-   ##
==========================================
- Coverage   79.65%   79.52%   -0.14%     
==========================================
  Files        1015     1015              
  Lines      115740   115805      +65     
  Branches     4275     4272       -3     
==========================================
- Hits        92198    92096     -102     
- Misses      22001    22167     +166     
- Partials     1541     1542       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@njzjz njzjz marked this pull request as draft June 30, 2026 05:39
@njzjz

njzjz commented Jun 30, 2026

Copy link
Copy Markdown
Member Author

I'd like to wait for #5613.

@njzjz njzjz force-pushed the feat/jax-hessian-freeze branch from a476689 to 30735c1 Compare July 8, 2026 14:27
njzjz added 2 commits July 9, 2026 19:49
Signed-off-by: Jinzhe Zeng <jinzhe.zeng@ustc.edu.cn>
Signed-off-by: Jinzhe Zeng <jinzhe.zeng@ustc.edu.cn>
@njzjz njzjz marked this pull request as ready for review July 10, 2026 15:49
Copilot AI review requested due to automatic review settings July 10, 2026 15:49
@dosubot dosubot Bot added the enhancement label Jul 10, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@njzjz njzjz requested a review from wanghan-iapcm July 10, 2026 15:50
OutputVariableCategory.REDU,
OutputVariableCategory.DERV_R,
OutputVariableCategory.DERV_C_REDU,
OutputVariableCategory.DERV_R_DERV_R,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding DERV_R_DERV_R here without a get_has_hessian() guard makes every JAX model request energy_derv_r_derv_r, including ones frozen without hessian. self.output_def is the consumer def from DeepPot.output_def, which hard-codes r_hessian=True, so this category is always present (it is not gated on hessian_mode). For a non-hessian model the stablehlo/savedmodel never produces that key, so _eval_model falls into the fill branch and allocates np.full([nframes, 3*natoms, 3*natoms], nan) — an O(N^2) array (~72 MB at 1000 atoms) on the common non-atomic force/energy path — which DeepPot.eval then discards because get_has_hessian() is False.

This reintroduces the regression fixed for the PT backend in #5045 ("fix: remove hessian outdef if not necessary", 87cb6ef). The PR already adds get_has_hessian() (below), so the fix is to mirror pt (deepmd/pt/infer/deep_eval.py) and drop DERV_R_DERV_R from the request defs when not self.get_has_hessian().

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in bab82b1 by filtering DERV_R_DERV_R from JAX request definitions whenever get_has_hessian() is false, matching the PyTorch backend behavior. Added regression coverage for standard non-Hessian models.

Validation:

  • pytest source/tests/jax/test_training.py -k "deep_eval_requests_hessian or deep_eval_skips_hessian or main_dispatches_freeze or hlo_hessian_mode" -v
  • ruff check .
  • ruff format --check .
  • commit pre-hooks (including pylint) passed

Coding agent: Codex
Codex version: codex-cli 0.144.1
Model: gpt-5.6-sol
Reasoning effort: xhigh

Avoid requesting Hessian output from standard frozen JAX models and add regression coverage.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.1
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants